package com.yhsimon.controller;


import com.yhsimon.entity.Commodity;
import com.yhsimon.entity.CommodityVO;
import com.yhsimon.entity.Type;
import com.yhsimon.repository.CommodityRepository;
import com.yhsimon.repository.TypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/commodity")
public class CommodityHandler {

    @Value(value = "${server.port}")
    private String port;

    @Autowired
    private CommodityRepository commodityRepository;

    @Autowired
    private TypeRepository typeRepository;

    @GetMapping("/index")
    public String index() {
        return "端口号：" + this.port;
    }

    @GetMapping("/findAll/{page}/{limit}")
    public CommodityVO findAll(@PathVariable("page") int page, @PathVariable("limit") int limit) {
        CommodityVO commodityVO = new CommodityVO();
        commodityVO.setCode(0);
        commodityVO.setMsg("");
        commodityVO.setCount(commodityRepository.count());
        commodityVO.setData(commodityRepository.findAll((page - 1) * limit, limit));
        return commodityVO;
    }

    @GetMapping("/findByName/{page}/{limit}/{name}")
    public CommodityVO findByName(@PathVariable("page") int page, @PathVariable("limit") int limit,@PathVariable("name") String name) {
        CommodityVO commodityVO = new CommodityVO();
        commodityVO.setCode(0);
        commodityVO.setMsg("");
        commodityVO.setCount(commodityRepository.count2(name));
        System.out.println("commodity ：name===="+name);
        commodityVO.setData(commodityRepository.findByName((page - 1) * limit, limit,"%"+name+"%"));
        return commodityVO;
    }

    @GetMapping("/findById/{id}")
    public Commodity findById(@PathVariable("id") int id) {
        return commodityRepository.findById(id);
    }

    @GetMapping("/findAllTypes")
    public List<Type> findAllTypes() {
        return typeRepository.findAllTypes();
    }

    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") int id) {
        commodityRepository.deleteById(id);
    }

    @PutMapping("/update")
    public void update(@RequestBody Commodity commodity) {
        System.out.println(commodity.toString());
        commodityRepository.update(commodity);
    }

    @PostMapping(value = "/save")
    public void save(@RequestBody Commodity commodity) {
        commodityRepository.save(commodity);
    }
}
